package com.gnerv.cms.controller;

import com.gnerv.cms.common.Result;
import com.gnerv.cms.dto.LoginDTO;
import com.gnerv.cms.dto.UpdatePasswordDTO;
import com.gnerv.cms.dto.UserLoginDTO;
import com.gnerv.cms.service.IUserService;
import com.gnerv.cms.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 基础平台-登录 controller 类
 *
 * @author zhang
 * @date 2019/12/2
 **/
@Slf4j
@Api(tags = "登录管理")
@CrossOrigin
@RestController
@RequestMapping("/api/manage")
public class LoginController {

    @Resource
    private IUserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody LoginDTO loginDTO, HttpServletRequest request) {
        Subject subject = ShiroUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginDTO.getAccount(), loginDTO.getPassword());
        subject.login(token);
        return new Result();
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Result logout() {
        ShiroUtils.logout();
        return Result.response();
    }

    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public Result updatePassword(@RequestBody UpdatePasswordDTO passwordDTO) {
        String ukId = ShiroUtils.getLoginUser().getUkId();
        userService.updatePassword(ukId, passwordDTO);
        return new Result();
    }

    @RequestMapping(value = "/login/user", method = RequestMethod.GET)
    public Result getLoginUser() {
        UserLoginDTO userLoginDTO = (UserLoginDTO) ShiroUtils.getLoginUser();
        return Result.response().data("loginUser", userLoginDTO);
    }

}
